package com.example.im;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.db.CommonData;
import com.example.model.User;
import com.example.util.BaseActivity;
import com.example.util.KeyboardsUtils;
import com.example.util.MyUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;

import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;

import static com.example.db.CommonData.commonData;
import static com.example.util.MyUtil.exeUrlTask;
import static com.example.util.MyUtil.toast;

public class RequestActivity extends BaseActivity {
    private TextView name;
    private TextView password1;
    private TextView password2;
    private boolean isRequest;//是否注册成功

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist);
        name=findViewById(R.id.username);
        password1=findViewById(R.id.password1);
        password2=findViewById(R.id.password2);
        Button request = findViewById(R.id.sure);
        Button toLogin = findViewById(R.id.to_login);
        isRequest=false;//初始化为false

        initRegisterButtonEvent(request);

        //跳转登录页面
        toLogin.setOnClickListener(v -> {
            Intent intent=new Intent(RequestActivity.this,LoginActivity.class);
            //创建Bundle
            Bundle data=new Bundle();
            data.putBoolean("isRequest",isRequest);
            if(isRequest){
                User user=new User();
                user.setName(name.getText().toString());
                user.setPassword(password2.getText().toString());
                data.putSerializable("user",user);
            }
            //intent携带Bundle
            intent.putExtras(data);
            this.setResult(Activity.RESULT_OK, intent);
            //本Activity结束，退出该Activity
            this.finish();
        });
    }

    private void initRegisterButtonEvent(Button request) {
        request.setOnClickListener(v -> {
            String userName = name.getText().toString();
            String pwd1 = password1.getText().toString();
            String pwd2 = password2.getText().toString();

            //判断用户名是否存在
            if (checkUserNameUnique(userName)) {
                toast(this, "用户名已存在");
                return;
            }

            //判断密码是否匹配
            if(Objects.equals(pwd1, pwd2)){
                //调用接口，申请注册
                Map<String,String> new_user=new HashMap<>();
                new_user.put("username",userName);
                new_user.put("password",pwd1);
                exeUrlTask(
                        RequestActivity.this,
                        () -> MyUtil.postReqJson("/user/regist",
                                new_user),
                        res -> (RequestActivity.this).runOnUiThread(() -> {
                            JSONObject data = res.getDataObject();
                            int id=data.getInteger("id");
                            isRequest=true;
                            registerUser(userName,pwd1);
                            toast(RequestActivity.this,"注册成功,id为"+id);
                        })
                );
            }else {
                toast(RequestActivity.this,"密码不匹配");
            }
        });
    }

    private void registerUser(String userName, String pwd) {
        User user = new User();
        user.setId(new Random().nextInt());
        user.setName(userName);
        user.setPassword(pwd);
        commonData.userDb.put(userName, user);
    }

    private boolean checkUserNameUnique(String userName) {
        return commonData.userDb.containsKey(userName);
    }

    /**
     * 点击非编辑区域收起键盘
     * 获取点击事件
     */
    @CallSuper
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() ==  MotionEvent.ACTION_DOWN ) {
            View view = getCurrentFocus();
            if (KeyboardsUtils.isShouldHideKeyBord(view, ev)) {
                KeyboardsUtils.hintKeyBoards(view);
            }
        }
        return super.dispatchTouchEvent(ev);
    }
}
